package com.fine.hair.manage.config;

import com.fine.hair.manage.config.security.UserPrincipal;
import com.fine.hair.comm.model.SecPermission;
import com.fine.hair.comm.model.SecRole;
import com.fine.hair.comm.model.SecUser;
import com.fine.hair.manage.mapper.SecPermissionMapper;
import com.fine.hair.manage.mapper.SecRoleMapper;
import com.fine.hair.manage.mapper.SecUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author junelee
 * @date 2020/6/9 14:56
 */
@Service
public class CustomUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SecUserMapper secUserMapper;

    @Autowired
    private SecRoleMapper secRoleMapper;

    @Autowired
    private SecPermissionMapper secPermissionMapper;

    @Override
    public UserDetails loadUserByUsername(String usernameOrPhone) throws UsernameNotFoundException {
        SecUser secUser = secUserMapper.findByUsernameOrNameOrPhone(usernameOrPhone, usernameOrPhone);
        if (secUser == null) {
           throw new UsernameNotFoundException("未找到用户信息 : " + usernameOrPhone);
        }
                //.orElseThrow(() -> new UsernameNotFoundException("未找到用户信息 : " + usernameOrNameOrPhone));
        List<SecRole> roles = secRoleMapper.selectByUserId(secUser.getId());
        List<Long> roleIds = roles.stream()
                .map(SecRole::getId)
                .collect(Collectors.toList());

        List<SecPermission> permissions = secPermissionMapper.selectByRoleIdList(roleIds);
        return UserPrincipal.create(secUser, roles, permissions);

    }
}
